package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.VWashWork;
import com.tianxin.workbao.workBao.bean.WashCoaltype;
import com.tianxin.workbao.workBao.bean.WashCoaltypeDao;
import com.tianxin.workbao.workBao.bean.WashWork;
import com.tianxin.workbao.workBao.bean.WashWorkDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/18.
 */

public class WashWorkProvide extends BaseDataProvide {
    private List<VWashWork> vWashWorks;
    private UpdateListViewListener mUpdateListViewListener;
    private int mPage = 1;
    private WashWorkDao washWorkDao;
    private WashCoaltypeDao washCoaltypeDao;
    private boolean isGetData = true;

    public WashWorkProvide(Context context, UpdateListViewListener listener) {
        super(context);
        this.mUpdateListViewListener = listener;
        washWorkDao = mGreenDaoHelper.getDaoSession().getWashWorkDao();
        washCoaltypeDao = mGreenDaoHelper.getDaoSession().getWashCoaltypeDao();
    }


    /**
     * 真正处理返回数据
     *
     * @param responseObj
     */
    private void handleResponseObj(Object responseObj) {
        try {
            JSONObject jsonObject = new JSONObject(responseObj.toString());
            int status = jsonObject.getInt(Constant.RESPONSE_STATUS);
            if (status > 0) {
                if (isGetData == false) {
                    mUpdateListViewListener.showMessage("ok");
                    return;
                }
                String dataJson = jsonObject.getString(Constant.RESPONSE_DATA);
                if (dataJson.startsWith("[") && dataJson.endsWith("]")) {
                    if (jsonObject.getJSONArray(Constant.RESPONSE_DATA) != null) {
                        vWashWorks = JSON.parseArray(dataJson, VWashWork.class);
                        refreshUI();
                        // 保存到数据库中
                        saveToDb(vWashWorks);
                    } else {
                        mUpdateListViewListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
                    }
                } else {
                    mUpdateListViewListener.showMessage(jsonObject.getString(Constant.RESPONSE_INFO));
                }
            } else {
                if (isGetData == false) {
                    mUpdateListViewListener.showMessage("failure");
                    return;
                }
                mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_data));
            }
        } catch (JSONException e) {
            showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
            e.printStackTrace();
        }
    }

    private void saveToDb(List<VWashWork> vWashWorks) {
        for (VWashWork vwork : vWashWorks) {
            washWorkDao.insertOrReplace(vwork.getWashWork());
            for (WashCoaltype coal : vwork.getInWashCoaltypes()) {
                washCoaltypeDao.insertOrReplace(coal);
            }
            for (WashCoaltype coal : vwork.getOutWashCoaltypes()) {
                washCoaltypeDao.insertOrReplace(coal);
            }
        }
    }

    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        if (disposeDataHandle == null) {
            disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        }
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        if (disposeDataListener == null) {
            disposeDataListener = new DisposeDataListener() {
                @Override
                public void onSuccess(Object responseObj) {
                    mUpdateListViewListener.hideProgress();
                    if (responseObj.equals(null)) {
                        mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.no_response));
                    } else {
                        handleResponseObj(responseObj);
                    }
                }

                @Override
                public void onFailure(Object reasonObj) {
                    mUpdateListViewListener.hideProgress();
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            };
        }
        return disposeDataListener;
    }

    public void getdatas(int page) {
        mPage = page;
        isGetData = true;
        if (NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.showProgress();
            getFromServer();
        } else {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb();
            refreshUI();
        }
    }

    /**
     * get from server
     */
    public void getFromServer() {
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        map.put("page", mPage + "");
        RequestParams params = new RequestParams(map);
        String url = URL.getWashWorkUrl();
        CommonOkHttpClient.post(CommonRequest.createPostRequest(url, params), getDisposeDataHandle());
    }

    private void getFromDb() {
        Query<WashWork> query = washWorkDao.queryBuilder()
                .orderDesc(WashWorkDao.Properties.Addtime)
                .offset((mPage - 1) * 8)
                .limit(8).build();
        vWashWorks = new ArrayList<>();
        List<WashWork> wlist = query.list();
        VWashWork vWashWork;
        for (int i = 0; i < wlist.size(); i++) {
            vWashWork = new VWashWork();
            vWashWork.setWashWork(wlist.get(i));
            Query<WashCoaltype> washCoaltypeQuery = washCoaltypeDao.queryBuilder()
                    .where(WashCoaltypeDao.Properties.Parentid.eq(wlist.get(i).getId()))
                    .where(WashCoaltypeDao.Properties.Type.eq(WashCoaltype.TYPE_IN))
                    .orderAsc(WashCoaltypeDao.Properties.Addtime).build();
            List<WashCoaltype> inList = washCoaltypeQuery.list();
            vWashWork.setInWashCoaltypes(inList);
            washCoaltypeQuery = washCoaltypeDao.queryBuilder()
                    .where(WashCoaltypeDao.Properties.Parentid.eq(wlist.get(i).getId()))
                    .where(WashCoaltypeDao.Properties.Type.eq(WashCoaltype.TYPE_OUT))
                    .orderAsc(WashCoaltypeDao.Properties.Addtime).build();
            List<WashCoaltype> outList = washCoaltypeQuery.list();
            vWashWork.setOutWashCoaltypes(outList);
            vWashWorks.add(vWashWork);
        }
    }

    @Override
    public void refreshUI() {
        if (mPage > 1) {
            mUpdateListViewListener.onLoadMoreData(vWashWorks);
        } else {
            mUpdateListViewListener.onRefreshData(vWashWorks);
        }
    }

    public void search(String query) {

    }

    public void save(VWashWork mVWashWork) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("vwashwork", JSON.toJSONString(mVWashWork));
            RequestParams params = new RequestParams(map);
            String url = URL.getSaveWashWorkUrl();
            CommonOkHttpClient.post(CommonRequest.createPostRequest(url, params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }

    public void delete(int id) {
        isGetData = false;
        if (NetworkUtils.isConnected(mContext)) {
            mUpdateListViewListener.showProgress();
            Map<String, String> map = new HashMap<>();
            map.put(Constant.APPTOKEN_NAME, getAppToken());
            map.put("id", id + "");
            RequestParams params = new RequestParams(map);
            String url = URL.getDeleteWashWorkUrl();
            CommonOkHttpClient.post(CommonRequest.createPostRequest(url, params), getDisposeDataHandle());
        } else {
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
        }
    }
}
